package com.boe.config.mvc.config;

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.util.LinkedList;

@Component
@ConditionalOnClass(RequestMappingHandlerAdapter.class)
public class ServletBeanWebProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (bean instanceof RequestMappingHandlerAdapter) {
            var handlerAdapter = (RequestMappingHandlerAdapter) bean;

            var resolvers = handlerAdapter.getArgumentResolvers();
            if (resolvers == null) {
                resolvers = new LinkedList<>();
            }

            if (resolvers.stream().anyMatch(it -> it instanceof LoginUserParameterConverter) == false) {
                var listResolvers = new LinkedList<HandlerMethodArgumentResolver>();
                listResolvers.add(new LoginUserParameterConverter());
                listResolvers.addAll(resolvers);
                handlerAdapter.setArgumentResolvers(listResolvers);
            }
        }
        return bean;
    }
}